using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Microsoft.Extensions.DependencyInjection;
using welog.core.model;

namespace welog.Features.ControlsLibrary;

public partial class MarkDownView : UserControl
{
    private bool _Save = false;
    
    public MarkDownView()
    {
        InitializeComponent();
        
    }

    private void TreeView_OnSelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        var treeView = sender as TreeView;
        var logTreeNode= treeView.SelectedItem as LogTreeNode;
        if (logTreeNode.ChildrenFile.Count > 0)
        {  
            var myapp = App.Current as App; var welogPageBase=myapp.ServiceProvider.GetServices<WelogPageBase>();
           var mds= welogPageBase.Where(x=>x.GetType().Name=="MarkDownViewModel");
           if (mds.Count()>0)
           {
               var md = mds.FirstOrDefault() as MarkDownViewModel;
               //Environment.CurrentDirectory=Path.GetDirectoryName(logTreeNode.ChildrenFile[0]);
               //md.Text = File.ReadAllText(Path.GetFileName(logTreeNode.ChildrenFile[0]));
               md.Text = File.ReadAllText(logTreeNode.ChildrenFile[0]);
               gb.Header = logTreeNode.GetCurrentDateString();
               mdg.Header = logTreeNode.DayOfWeek();
               _Save = true;
           }
        }
        else
        {
            _Save = false;
        }
    }

    private void TextBox_OnTextChanged(object? sender, TextChangedEventArgs e)
    {
        if (_Save)
        {
            var logTreeNode = markDownTreeView.SelectedItem as LogTreeNode;
            var tbox = sender as TextBox;
            //File.WriteAllText(Path.GetFileName(logTreeNode.ChildrenFile[0]),tbox.Text);
            File.WriteAllText(logTreeNode.ChildrenFile[0],tbox.Text);
        }
    }

    private void Control_OnLoaded(object? sender, RoutedEventArgs e)
    {
    }
}